package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by WF on 2020/3/30 16:12
 */
@Service
@Transactional
public class ArticleService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ArticleDao articleDao;
    //1.文章审核
    public void examine(String articleId) {
        articleDao.examine(articleId);
    }
    //2.文章点赞
    public void thumbup(String articleId) {
        articleDao.thumbup(articleId);
    }
    //3.根据主键查询(使用缓存查询)
    public Article findById(String id) {
        //3.1)从redis中根据key得到文章
        Article article = (Article) redisTemplate.opsForValue().get("article_"+id);
        //3.2)如果不存在此文章，就从数据库中查询
        if(article == null){
            Article arti = articleDao.findById(id).get();
            //再将此文章放到redis中
            redisTemplate.opsForValue().set("article_" + id,arti);
            System.out.println("正在将数据放到redis中...");
        }
        //3.3)返回
        return article;
    }
    public void update(Article article) {
        //清空缓存
        redisTemplate.delete("article_"+article.getId());
        articleDao.save(article);
    }

    public void delete(String id) {
        //清空缓存
        redisTemplate.delete("article_"+id);
        articleDao.deleteById(id);
    }
}
